import cv2
import numpy as np

def process_image(image_path):
    # 读取图像
    image = cv2.imread(image_path)
    if image is None:
        print("无法读取图像")
        return
    
    # 转换为灰度图像
    gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)
    
    # 边缘检测
    edges = cv2.Canny(gray, 50, 150, apertureSize=3)
    
    # 霍夫线变换检测直线
    lines = cv2.HoughLinesP(edges, 1, np.pi/180, threshold=100, minLineLength=50, maxLineGap=10)
    
    # 计算直线的倾斜角度
    angles = []
    for line in lines:
        for x1, y1, x2, y2 in line:
            angle = np.degrees(np.arctan2(y2 - y1, x2 - x1))
            angles.append(angle)
    
    # 计算平均倾斜角度
    avg_angle = np.mean(angles)
    print(f"倾斜角度: {avg_angle}")

    # 轮廓检测
    contours, _ = cv2.findContours(edges, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)
    
    # 计算格子大小（假设所有格子大小相近）
    if contours:
        # 按面积排序，选择面积中等的一个作为格子（排除小噪声和大背景）
        contours.sort(key=cv2.contourArea)
        # 选择面积中等的轮廓，比如取中间的值
        sample_contour = contours[len(contours)//2]
        x, y, w, h = cv2.boundingRect(sample_contour)
        print(f"格子大小: 宽{w}, 高{h}")

        # 计算二维格子的长宽和起点
        # 这里假设格子是按行或列排列的，可以通过聚类或更复杂的逻辑来计算
        # 简单示例：假设二维格子的起点是最左上角的格子
        contours_sorted_by_x = sorted(contours, key=lambda c: cv2.boundingRect(c)[0])
        contours_sorted_by_y = sorted(contours_sorted_by_x, key=lambda c: cv2.boundingRect(c)[1])
        start_x, start_y, start_w, start_h = cv2.boundingRect(contours_sorted_by_y[0])
        print(f"二维格子起点: ({start_x}, {start_y})")

        # 计算二维格子的长宽（假设是矩形排列）
        all_x = [cv2.boundingRect(c)[0] for c in contours_sorted_by_y]
        all_y = [cv2.boundingRect(c)[1] for c in contours_sorted_by_y]
        grid_width = max(all_x) + w - min(all_x)
        grid_height = max(all_y) + h - min(all_y)
        print(f"二维格子长宽: 宽{grid_width}, 高{grid_height}")

    # 显示图像（可选）
    cv2.imshow("Edges", edges)
    cv2.waitKey(0)
    cv2.destroyAllWindows()

# 调用函数处理图像
process_image("your_image_path.png")